import json
import os
from django.core.mail import send_mail
from django.db.models import Q
from django.http import HttpResponse, JsonResponse

from Friend.models import Friend
from .models import User
def sign(request):
    if request.method == "POST":
        body = json.loads(request.body)
        if len(User.objects.filter(email=body["email"])) != 0:
            return HttpResponse("用户已存在")
        if "email" in body and "password" in body and "account" in body:
            User.objects.create(
                email=body["email"],
                account=body["account"],
                password=body["password"]
            ).save()
            if len(User.objects.filter(email=body["email"])) != 0:
                return HttpResponse("创建成功")
            else:
                return HttpResponse("创建失败")
        else:
            return HttpResponse("参数不全")
    else:
        return HttpResponse("请使用POST")
def getUserMsgByAccount(request):
    u = User.objects.filter(account=request.GET.get("account"))
    if len(u) != 0:
        if request.GET.get("whoseFriend")=="null":
            return JsonResponse({
                "password": u[0].password,
                 "email": u[0].email,
                 "account": u[0].account,
                 "nickname": u[0].nickname,
                 "iconUrl": u[0].iconUrl
                 })
        else:
            return JsonResponse(
                {"password": u[0].password,
                 "email": u[0].email,
                 "account": u[0].account,
                 "nickname": u[0].nickname,
                 "iconUrl": u[0].iconUrl,
                 "friendMsg":[{
                     "remark":each1.remark
                 }for each1 in Friend.objects.filter(account=request.GET.get("whoseFriend"),friendAccount=u[0].account)]
                 })
    else:
        return HttpResponse("未找到该用户")

def verify(request):
    if request.method == 'GET':
        user = User.objects.filter(account=request.GET.get("account"), password=request.GET.get("password"))
        if len(user) != 0:
            return HttpResponse("验证成功")
        else:
            return HttpResponse("验证失败")
def changePasswordByEmail(request):
    print("_______")
    print(request.GET.get("mail"))
    print(request.GET.get("password"))
    print("_______")
    u = User.objects.filter(email=request.GET.get("mail"))
    if len(u) != 0:
        u.update(password=request.GET.get("password"))
        return HttpResponse("修改成功")
    else:
        return HttpResponse("用户不存在")
def modifyByEmail(request):
    u = User.objects.filter(email=request.GET.get("email"))
    if len(u) != 0:
        u.update(password=request.GET.get("password"), nickname=request.GET.get("nickname"))
        return HttpResponse("保存完毕")
    else:
        return HttpResponse("用户不存在")
def uploadIconByEmail(request):
    if request.method == "POST":
        u = User.objects.filter(email=request.GET.get("email"))
        if len(u) != 0:
            iconFile = request.FILES.get('file', None)
            if not iconFile:
                return HttpResponse("no file ")
            filename = request.GET.get("email") + "_" + iconFile.name
            filename = filename.replace(" ", "")
            filename = filename.replace(":", "")
            filename = filename.replace("-", "")
            filename = filename.replace("+", "")
            filename = filename.replace("_", "")
            destination = open(os.path.join("files/icon", filename), "wb+")
            for chunk in iconFile.chunks():
                destination.write(chunk)
            destination.close()
            u.update(iconUrl="files/icon/" + filename)
            return HttpResponse("ok")
        else:
            return HttpResponse("user not found")
def searchUsers(request):
    if request.method == 'GET':
        start = int(request.GET.get('start'))
        end = int(request.GET.get('end'))
        u = User.objects.filter(Q(nickname__icontains=request.GET.get('word')) | Q(account__icontains=request.GET.get('word')))
        count = u.count()
        if count < start:
            return HttpResponse("没搜到用户")
        elif count <= end:
            return JsonResponse({"data": [{
                'account': each.account,
                'nickname': each.nickname,
                'iconUrl': each.iconUrl,
                'email': each.email
            } for each in u.order_by('-createTime')[int(start): int(end)]]
            })

def sendEmail(request):
    send_mail(
        'Talking验证码',
        '您的Talking验证码是:' + request.GET.get('yzm'),
        'timi_xyt@163.com',
        [request.GET.get('mail')],
        fail_silently=False,
    )
    return JsonResponse({"msg": "已发送邮箱"})